package com.yzzrjy.old;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yzzrjy.bean.GiftBean;
import com.yzzrjy.bean.UserBaseBean;
import com.yzzrjy.util.DruidUtils;
import com.yzzrjy.util.ResponseUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;


@WebServlet(name = "GetGiftList", value = "/getGiftList")
public class GetGiftListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        String uid = request.getParameter("uid");
        String token = request.getParameter("token");
        if(uid == null || token == null || uid.length() == 0 || token.length() == 0){
            ResponseUtils.parameterError(response);
            return;
        }
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        try {
            UserBaseBean userInfoBean = queryRunner.query("select * from user_base where uid=?", new BeanHandler<>(UserBaseBean.class), uid);
            if(userInfoBean == null){
                ResponseUtils.userNotExist(response);
                return;
            }
            List<GiftBean> giftBeans = queryRunner.query("select * from gift_info", new BeanListHandler<>(GiftBean.class));
            if(giftBeans.size() == 0){
                ResponseUtils.notFindError(response, "还没有礼物");
                return;
            }
            JSONArray infoArray = new JSONArray();
            for(GiftBean giftBean : giftBeans){
                infoArray.add(giftBean);
            }
            JSONObject infoObject = new JSONObject();
            infoObject.put("coin", userInfoBean.getCoin());
            infoObject.put("list", infoArray);

            ResponseUtils.success(response, infoObject);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
